package com.zfl.thread.day02;

/**
 * 单例设计模式
 * 饿汉式、懒汉式
 * 构造方法私有化，私有静态实例，类加载时创建
 */


class SingleTon01 {

    private static SingleTon01 instance = new SingleTon01();

    private SingleTon01() {
        System.out.println("对象被创建了");//创建的时候输出
    }

    public static SingleTon01 getInstance() {
        return SingleTon01.instance;
    }
}

class SingleTon02 {
    private static volatile SingleTon02 instance;

    private SingleTon02() {
        System.out.println(Thread.currentThread().getName() + "懒汉式单例实例创建");
    }

    public static SingleTon02 getInstance() {
        if (SingleTon02.instance != null) {
            return SingleTon02.instance;
        } else {
            synchronized (SingleTon02.class) {
                if (SingleTon02.instance == null) {
                    return SingleTon02.instance = new SingleTon02();
                }
                return SingleTon02.instance;
            }
        }
    }
}

public class SingleTonDemo01 {
    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            new Thread(SingleTon02::getInstance, "线程" + i).start();
        }
    }
}
